"""
经典贪吃蛇游戏 - 完整修复版
功能包含：
1. 开始/游戏/结束三个界面
2. 蛇身自动增长机制
3. 食物随机生成系统
4. 碰撞检测与计分系统
5. 按钮交互与视觉效果
"""

import pygame
import random
import sys

# 初始化Pygame
pygame.init()

# 版本兼容性检查
if pygame.version.vernum < (2, 0):
    print("请升级Pygame: pip install --upgrade pygame")
    sys.exit()

# 游戏常量配置
WIDTH, HEIGHT = 800, 600
GRID_SIZE = 20
GRID_WIDTH = WIDTH // GRID_SIZE
GRID_HEIGHT = HEIGHT // GRID_SIZE
FPS = 15

# 颜色配置
COLORS = {
    "start_bg": (100, 150, 255),    # 开始界面背景
    "game_bg": (0, 0, 0),           # 游戏界面背景
    "end_bg": (150, 100, 255),      # 结束界面背景
    "button": (255, 255, 255),      # 按钮颜色
    "button_hover": (200, 200, 200), # 按钮悬停色
    "snake": (0, 255, 0),           # 蛇身基础色
    "food": (255, 0, 0)             # 食物颜色
}

# 字体配置
try:
    BUTTON_FONT = pygame.font.SysFont("simhei", 36)  # 尝试加载黑体
except:
    BUTTON_FONT = pygame.font.Font(None, 36)        # 失败使用默认字体

class Game:
    def __init__(self):
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption("经典贪吃蛇 v2.0")
        self.clock = pygame.time.Clock()
        
        # 游戏状态管理
        self.state = "start"
        self.score = 0
        self.direction = "right"
        self.snake = [(GRID_WIDTH//2, GRID_HEIGHT//2)]
        self.food = self.generate_food()
        
        # 界面元素配置
        self.buttons = {
            "start": pygame.Rect(WIDTH//2-100, HEIGHT//2-30, 200, 60),
            "restart": pygame.Rect(WIDTH//2-180, HEIGHT//2+50, 160, 50),
            "close": pygame.Rect(WIDTH//2+20, HEIGHT//2+50, 160, 50)
        }

    def generate_food(self):
        """安全生成食物位置"""
        max_attempts = 100
        for _ in range(max_attempts):
            pos = (random.randint(0, GRID_WIDTH-1), 
                  random.randint(0, GRID_HEIGHT-1))
            if pos not in self.snake:
                return pos
        raise RuntimeError("无法生成食物")

    def draw_button(self, rect, text, hover=False):
        """绘制带阴影效果的圆形按钮"""
        color = COLORS["button_hover"] if hover else COLORS["button"]
        # 按钮主体
        pygame.draw.circle(self.screen, color, rect.center, min(rect.w, rect.h)//2)
        # 按钮文字
        text_surf = BUTTON_FONT.render(text, True, (0,0,0))
        text_rect = text_surf.get_rect(center=rect.center)
        # 文字阴影
        shadow_rect = text_rect.move(2, 2)
        self.screen.blit(BUTTON_FONT.render(text, True, (0,0,0)), shadow_rect)
        self.screen.blit(text_surf, text_rect)

    def draw_start_screen(self):
        """开始界面"""
        self.screen.fill(COLORS["start_bg"])
        # 绘制开始按钮
        mouse_pos = pygame.mouse.get_pos()
        hover = self.buttons["start"].collidepoint(mouse_pos)
        self.draw_button(self.buttons["start"], "开始游戏", hover)

    def draw_game_screen(self):
        """游戏主界面"""
        self.screen.fill(COLORS["game_bg"])
        
        # 绘制蛇身（渐变效果）
        for i, (x, y) in enumerate(self.snake):
            color = (0, max(100, 255 - i*15), 0)
            rect = pygame.Rect(x*GRID_SIZE, y*GRID_SIZE, GRID_SIZE-2, GRID_SIZE-2)
            pygame.draw.rect(self.screen, color, rect, border_radius=5)
        
        # 绘制食物（发光效果）
        fx, fy = self.food
        food_rect = pygame.Rect(fx*GRID_SIZE, fy*GRID_SIZE, GRID_SIZE-2, GRID_SIZE-2)
        pygame.draw.rect(self.screen, COLORS["food"], food_rect, border_radius=8)
        # 光晕效果
        for i in range(1,4):
            glow_rect = food_rect.inflate(i*4, i*4)
            pygame.draw.rect(self.screen, (255, 100, 100, 50), glow_rect, border_radius=8)
        
        # 绘制分数
        font = pygame.font.Font(None, 40)
        score_text = font.render(f"得分: {self.score}", True, (255,255,255))
        self.screen.blit(score_text, (20, 20))

    def draw_end_screen(self):
        """结束界面"""
        self.screen.fill(COLORS["end_bg"])
        # 绘制按钮
        mouse_pos = pygame.mouse.get_pos()
        self.draw_button(self.buttons["restart"], "再来一局", 
                        self.buttons["restart"].collidepoint(mouse_pos))
        self.draw_button(self.buttons["close"], "退出游戏", 
                        self.buttons["close"].collidepoint(mouse_pos))
        # 结束文字
        text = BUTTON_FONT.render(f"游戏结束！最终得分: {self.score}", True, (255,255,255))
        self.screen.blit(text, (WIDTH//2-180, HEIGHT//2-100))

    def update_snake(self):
        """更新蛇的位置和状态"""
        head = list(self.snake[0])
        # 方向控制
        dir_map = {
            "up": (0, -1), "down": (0, 1),
            "left": (-1, 0), "right": (1, 0)
        }
        dx, dy = dir_map[self.direction]
        head[0] += dx
        head[1] += dy
        
        # 碰撞检测
        if (head[0] < 0 or head[0] >= GRID_WIDTH or
            head[1] < 0 or head[1] >= GRID_HEIGHT or
            tuple(head) in self.snake):
            self.state = "end"
            return
        
        self.snake.insert(0, tuple(head))
        
        # 吃食物检测
        if tuple(head) == self.food:
            self.score += 10
            self.food = self.generate_food()
        else:
            self.snake.pop()

    def handle_input(self):
        """处理用户输入"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
                
            if self.state == "start":
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if self.buttons["start"].collidepoint(event.pos):
                        self.state = "playing"
            
            elif self.state == "playing":
                # 键盘方向控制
                keys = pygame.key.get_pressed()
                if keys[pygame.K_UP] and self.direction != "down":
                    self.direction = "up"
                elif keys[pygame.K_DOWN] and self.direction != "up":
                    self.direction = "down"
                elif keys[pygame.K_LEFT] and self.direction != "right":
                    self.direction = "left"
                elif keys[pygame.K_RIGHT] and self.direction != "left":
                    self.direction = "right"
            
            elif self.state == "end":
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if self.buttons["restart"].collidepoint(event.pos):
                        self.__init__()  # 重置游戏
                    elif self.buttons["close"].collidepoint(event.pos):
                        pygame.quit()
                        sys.exit()

    def run(self):
        """游戏主循环"""
        while True:
            self.handle_input()
            
            # 状态更新
            if self.state == "playing":
                self.update_snake()
            
            # 画面渲染
            if self.state == "start":
                self.draw_start_screen()
            elif self.state == "playing":
                self.draw_game_screen()
            else:
                self.draw_end_screen()
            
            pygame.display.flip()
            self.clock.tick(FPS)

if __name__ == "__main__":
    # 运行游戏
    Game().run()